<template>
  <el-form
    v-loading="loading"
    :model="companyForm"
    :rules="companyRules"
    ref="companyForm"
    status-icon
    label-width="100px"
  >
    <el-form-item label="公司logo" prop="logo">
      <el-upload
        class="upload-item-info"
        :action="uploadAction"
        :headers="actionData"
        :before-upload="handleBeforeUpload"
        :on-change="handleChange"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        list-type="picture"
        :show-file-list="false"
        :auto-upload="true"
      >
        <el-button size="small" type="primary">选择图片</el-button>
      </el-upload>

      <td-image v-model="layerImg" @remove="removeImg"></td-image>
    </el-form-item>
    <el-form-item label="公司名称" prop="name">
      <el-input type="text" v-model="companyForm.name"></el-input>
    </el-form-item>
    <el-form-item label="公司地址" prop="address">
      <el-input v-model="companyForm.address" placeholder="公司地址"></el-input>
    </el-form-item>
    <el-form-item v-if="!submitText" label="管理员帐号" prop="adminName">
      <el-input
        v-model="companyForm.adminName"
        placeholder="请设置一个公司管理员帐号"
      ></el-input>
    </el-form-item>
    <el-form-item label="联系方式" prop="telPhone">
      <el-input
        v-model="companyForm.telPhone"
        placeholder="公司联系方式"
      ></el-input>
    </el-form-item>

    <el-form-item v-if="submitText >= 0" style="text-align:center;">
      <el-button type="danger" @click="onCloseCompanyDialog">取消</el-button>
      <el-button type="primary" @click="onSubmitCompanyInfo">提交</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { companyManage, uploadFile } from '@/api'

import TdImage from '@/components/TdImage.vue'

var baseUrl = process.env.VUE_APP_BASE_API

export default {
  name: 'form-com',
  componentName: 'formCom',
  components: { TdImage },
  data() {
    const validataTelPhone = (rule, value, callback) => {
      const phoneReg = new RegExp(/^1[3-9]\d{9}$/)
      const telReg = new RegExp(/^([0\+]\d{2,3}-?)?(\d{7,8})$/)
      if (value) {
        console.log(phoneReg.test(value), telReg.test(value))
        if (phoneReg.test(value) || telReg.test(value)) {
          return callback()
        } else {
          callback(new Error('请输入正确的电话号码'))
        }
      } else {
        callback()
      }
    }
    const validatorAdminname = (rule, value, callback) => {
      if (!/^[A-Za-z0-9\_]{4,20}$/.test(value)) {
        return callback(
          new Error('请输入不少于四位不超过二十位的英文数字用户名')
        )
      } else {
        callback()
      }
    }
    return {
      loading: false,
      companyForm: {
        logo: '',
        name: '',
        address: '',
        telPhone: '',
        adminName: ''
      },
      companyRules: {
        name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        address: [
          { required: true, message: '请输入公司联系人', trigger: 'blur' }
        ],
        telPhone: [{ validator: validataTelPhone, trigger: 'blur' }],
        adminName: [
          {
            required: true,
            message: '请输入公司管理员帐号名',
            trigger: 'blur'
          },
          { validator: validatorAdminname, trigger: 'blur' }
        ]
      },
      actionData: { Authorization: 'Bearer ' + localStorage.getItem('token') },
      uploadAction: baseUrl + '/txUpload', // 头像upload
      uploadPicUrl: baseUrl, // 头像远端地址
      logoIds: null, // logo id
      fileList: [], // FormData list
      images: null, // 图片路径 无http
      layerImg: []
    }
  },
  watch: {
    comId(newV, oldV) {
      console.log(newV, oldV)
      if (newV) {
        this.getCompanyInfo()
      } else {
        this.images = null
        this.layerImg = []
        this.logoIds = null
        this.companyForm = {
          name: '',
          address: '',
          telPhone: '',
          adminName: ''
        }
      }
    }
  },
  props: {
    submitText: Number,
    comId: String
  },
  created() {
    if (this.comId) this.getCompanyInfo()
  },
  methods: {
    //
    getCompanyInfo() {
      companyManage
        .selectCompanyById({ id: this.comId })
        .then(res => {
          console.log(res)
          if (res.code === 200) {
            let imageArr = []
            if (res.data.logo != '')
              imageArr.push(this.uploadPicUrl + res.data.logo)
            this.images = res.data.logo
            this.layerImg = imageArr
            this.companyForm = res.data
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 文件操作
    handleBeforeUpload(file) {
      let fileObj = {
        name: file.name,
        size: file.size,
        status: '开始上传',
        process: 0,
        id: file.uid,
        type: /^image/.test(file.type)
      }
      if (!fileObj.type) {
        this.$message.error('这不是图片')
        return false
      }
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('上传文件过大', file.size)
        return false //必须返回false
      }
      this.fileList = []
      this.fileList.push(file)
      this.uploadFileLogo()
    },
    handleChange() {},
    handlePreview() {},
    handleRemove() {},
    async uploadFileLogo() {
      const files = new FormData()
      for (let i = 0; i < this.fileList.length; i++) {
        files.append('file', this.fileList[i])
      }
      try {
        const upload = await uploadFile.txUpload(files)
        console.log(upload)
        let imageArr = []
        this.images = upload.data.url
        this.logoIds = upload.data.id
        imageArr.push(this.uploadPicUrl + this.images)
        this.layerImg = imageArr
        this.$message.success('图片上传成功')
      } catch {
        this.$message.error('错误')
      }
    },
    removeImg({ img, index }) {
      console.log(img, index)
      this.layerImg.splice(index, 1)
      this.logoIds = null
      this.images = null
    },
    // 关 dialog
    onCloseCompanyDialog() {
      this.companyForm = {
        name: '',
        address: '',
        telPhone: '',
        adminName: ''
      }
      this.$emit('onSubmit', false)
    },
    // 提交 dialog form
    onSubmitCompanyInfo() {
      this.$refs['companyForm'].validate(valid => {
        if (valid) {
          this.submitCompanyForm()
        } else {
          return false
        }
      })
    },
    // 提交 form
    async submitCompanyForm() {
      this.loading = true
      let companyForm = this.companyForm
      companyForm.logo = this.images ? this.images : ''
      try {
        var company
        if (this.submitText) {
          company = await companyManage.updateCompany(companyForm)
        } else {
          company = await companyManage.addCompany(companyForm)
        }

        this.loading = false
        this.companyForm = {
          name: '',
          address: '',
          telPhone: '',
          adminName: ''
        }
        this.images = null
        this.layerImg = []
        this.logoIds = null
        this.$emit('onSubmit', true)
        if (company.data != null) {
          this.$message.success({
            message: this.submitText ? '修改公司成功了' : '添加公司成功了',
            duration: 2000
          })
        } else {
          this.$message.error({
            message: company.message,
            duration: 2000
          })
        }
      } catch {
        this.loading = false
        this.$emit('onSubmit', false)
        this.$message.error({
          message: '噢，发现错误，联系后台管理员',
          duration: 2000
        })
      }
    }
  }
}
</script>
